package com.jacob.cloud.mall.cartorder.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import com.jacob.cloud.mall.cartorder.feign.ProductFeignClient;
import com.jacob.cloud.mall.cartorder.feign.UserFeignClient;
import com.jacob.cloud.mall.cartorder.model.dao.CartMapper;
import com.jacob.cloud.mall.cartorder.model.dao.OrderItemMapper;
import com.jacob.cloud.mall.cartorder.model.dao.OrderMapper;
import com.jacob.cloud.mall.cartorder.model.pojo.Order;
import com.jacob.cloud.mall.cartorder.model.pojo.OrderItem;
import com.jacob.cloud.mall.cartorder.model.request.CreateOrderReq;
import com.jacob.cloud.mall.cartorder.model.vo.CartVO;
import com.jacob.cloud.mall.cartorder.model.vo.OrderItemVO;
import com.jacob.cloud.mall.cartorder.model.vo.OrderVO;
import com.jacob.cloud.mall.cartorder.service.ICartService;
import com.jacob.cloud.mall.cartorder.service.IOrderService;
import com.jacob.cloud.mall.cartorder.util.OrderCodeFactory;
import com.jacob.cloud.mall.cartorder.util.QRCodeGenerator;
import com.jacob.cloud.mall.categoryproduct.model.dao.ProductMapper;
import com.jacob.cloud.mall.categoryproduct.model.pojo.Product;
import com.jacob.cloud.mall.common.common.Constant;
import com.jacob.cloud.mall.common.exception.MallException;
import com.jacob.cloud.mall.common.exception.MallExceptionEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ICartService cartService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Value("${file.upload.ip}")
    private String ip;

    @Value("${file.upload.port}")
    private String port;

    @Value("${file.upload.directory}")
    private String FILE_UPLOAD_DIR;

    /**
     * 创建订单
     * @param createOrderReq
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String createOrder(CreateOrderReq createOrderReq) {
        // 拿到用户id
        Integer userId = userFeignClient.getUser().getId();

        // 从购物车查找已经勾选的商品
        List<CartVO> cartVOList = cartService.listCart(userId);
        ArrayList<CartVO> cartVOArrayListTemp = new ArrayList<>();
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            if (cartVO.getSelected().equals(Constant.CartSelected.SELECTED)) {
                cartVOArrayListTemp.add(cartVO);
            }
        }
        cartVOList = cartVOArrayListTemp;

        // 如果购物车已勾选为空，报错
        if (CollectionUtils.isEmpty(cartVOList)){
            throw new MallException(MallExceptionEnum.CART_EMPTY);
        }

        // 判断商品是否存在、上下架状态、库存
        vaildSaleStatusAndStock(cartVOList);

        // 把购物车对象转为订单item对象
        List<OrderItem> orderItemList = cartVOListToOrderItemList(cartVOList);

        // 扣库存
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            Product product = productFeignClient.detailForFeign(orderItem.getProductId());
            int stock = product.getStock() - orderItem.getQuantity();
            if (stock < 0) {
                throw new MallException(MallExceptionEnum.CART_NOT_ENOUGH);
            }
            product.setStock(stock);
            productFeignClient.updateStock(product.getId(), product.getStock());
        }

        // 把购物车的已勾选商品删除
        clearCart(cartVOList);

        // 生成订单
        Order order = new Order();

        // 生成订单号，有独立规则
        String orderNo = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalPrice(totalPrice(orderItemList));
        order.setReceiverName(createOrderReq.getReceiverName());
        order.setReceiverMobile(createOrderReq.getReceiverMobile());
        order.setReceiverAddress(createOrderReq.getReceiverAddress());
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPostage(0);
        order.setPaymentType(1);

        orderMapper.insertSelective(order);

        // 循环保存每个商品到order_item表
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            orderItem.setOrderNo(order.getOrderNo());
            orderItemMapper.insertSelective(orderItem);
        }
        
        return orderNo;
    }

    /**
     * 根据订单号获取订单详情
     * @param orderNo
     * @return
     */
    @Override
    public OrderVO detail(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        // 订单不存在，报错
        if (order == null) {
            throw new MallException(MallExceptionEnum.ORDER_NOT_EXIST);
        }
        // 订单存在，需要判断所属
        Integer userId = userFeignClient.getUser().getId();
        if (!order.getUserId().equals(userId)){
            throw new MallException(MallExceptionEnum.ORDER_NOT_YOUR);
        }
        OrderVO orderVo = getOrderVO(order);
        return orderVo;
    }

    /**
     * 前台订单列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo list(Integer pageNum, Integer pageSize) {
        Integer userId = userFeignClient.getUser().getId();

        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.selectByUserId(userId);
        List<OrderVO> orderVOList = orderListToOrderVOList(orderList);

        PageInfo pageInfo = new PageInfo<>(orderList);
        pageInfo.setList(orderVOList);
        return pageInfo;
    }

    /**
     * 取消订单
     * @param orderNo
     */
    @Override
    public void cancel(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            throw new MallException(MallExceptionEnum.ORDER_NOT_EXIST);
        }
        // 验证用户身份
        Integer userId = userFeignClient.getUser().getId();
        if (!order.getUserId().equals(userId)){
            throw new MallException(MallExceptionEnum.ORDER_NOT_YOUR);
        }
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())) {
            order.setOrderStatus(Constant.OrderStatusEnum.CANCEL_ORDER.getCode());
            order.setEndTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        } else {
            throw new MallException(MallExceptionEnum.ORDER_STATUS_WRONG);
        }
    }

    /**
     * 根据Order对象组织OrderVO对象
     * @param order
     * @return
     */
    private OrderVO getOrderVO(Order order) {
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        // 获取订单对应的orderItemVOList
        List<OrderItem> orderItemList = orderItemMapper.selectByOrderNo(order.getOrderNo());

        List<OrderItemVO> orderItemVOList = new ArrayList<>();
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            OrderItemVO orderItemVO = new OrderItemVO();
            BeanUtils.copyProperties(orderItem, orderItemVO);
            orderItemVOList.add(orderItemVO);
        }
        orderVO.setOrderItemVOList(orderItemVOList);
        orderVO.setOrderStatusName(Constant.OrderStatusEnum.codeOf(orderVO.getOrderStatus()).getValue());

        return orderVO;
    }

    /**
     * 将orderList转为orderVOList
     * @param orderList
     * @return
     */
    private List<OrderVO> orderListToOrderVOList(List<Order> orderList) {
        List<OrderVO> orderVOList = new ArrayList<OrderVO>();

        for (int i = 0; i < orderList.size(); i++) {
            Order order = orderList.get(i);
            OrderVO orderVO = getOrderVO(order);
            orderVOList.add(orderVO);
        }
        return orderVOList;
    }

    /**
     * 在支付的时候显示的二维码
     * @param orderNo
     * @return
     */
    @Override
    public String qrCode(String orderNo) {
        String address = ip +":"+ port;
        String payUrl = "http://"+address+"/cart-order/pay?orderNo="+orderNo;
        try {
            QRCodeGenerator.generateQRCodeImage(payUrl, 350, 350, FILE_UPLOAD_DIR+orderNo+".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pngAddress = "http://"+address+"/cart-order/images/"+orderNo+".png";
        return pngAddress;
    }

    /**
     * 后台分页订单列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo adminList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.selectAllForAdmin();
        List<OrderVO> orderVOList = orderListToOrderVOList(orderList);
        PageInfo orderPageInfo = new PageInfo(orderList);
        orderPageInfo.setList(orderVOList);
        return orderPageInfo;
    }

    /**
     * 订单支付
     * @param orderNo
     */
    @Override
    public void orderPay(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        //查不到订单，报错
        if (order == null){
            throw new MallException(MallExceptionEnum.ORDER_NOT_EXIST);
        }
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())){
            order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
            order.setPayTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else{
            throw new MallException(MallExceptionEnum.ORDER_STATUS_WRONG);
        }
    }

    /**
     * 订单发货
     * @param orderNo
     */
    @Override
    public void deliveryOrder(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        //查不到订单，报错
        if (order == null){
            throw new MallException(MallExceptionEnum.ORDER_NOT_EXIST);
        }
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.PAID.getCode())){
            order.setOrderStatus(Constant.OrderStatusEnum.DEVELIVERED.getCode());
            order.setDeliveryTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else{
            throw new MallException(MallExceptionEnum.ORDER_STATUS_WRONG);
        }
    }

    /**
     * 订单完结
     * @param orderNo 订单编号
     */
    @Override
    public void finish(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        //查不到订单，报错
        if (order == null) {
            throw new MallException(MallExceptionEnum.ORDER_NOT_EXIST);
        }
        //如果是普通用户，就要校验订单的所属
        if (userFeignClient.getUser().getRole().equals(1)
                && !order.getUserId().equals(userFeignClient.getUser().getId())) {
            throw new MallException(MallExceptionEnum.ORDER_NOT_YOUR);
        }

        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.DEVELIVERED.getCode())) {
            order.setOrderStatus(Constant.OrderStatusEnum.FINASHED.getCode());
            order.setEndTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        } else {
            throw new MallException(MallExceptionEnum.ORDER_STATUS_WRONG);
        }
    }

    /**
     * 计算订单总价
     * @param orderItemList
     * @return
     */
    private Integer totalPrice(List<OrderItem> orderItemList) {
        Integer totalPrice = 0;
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            totalPrice += orderItem.getTotalPrice();
        }

        return totalPrice;
    }

    /**
     * 把购物车的已勾选商品删除
     * @param cartVOList
     */
    private void clearCart(List<CartVO> cartVOList) {
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            cartMapper.deleteByPrimaryKey(cartVO.getId());
        }
    }

    /**
     * 把购物车对象转为订单item对象
     * @param cartVOList
     * @return
     */
    private List<OrderItem> cartVOListToOrderItemList(List<CartVO> cartVOList) {
        ArrayList<OrderItem> orderItemList = new ArrayList<OrderItem>();
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartVO.getProductId());
            // 记录商品快照信息
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImg(cartVO.getProductImg());
            orderItem.setUnitPrice(cartVO.getProductPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            orderItem.setTotalPrice(cartVO.getTotalPrice());
            orderItemList.add(orderItem);
        }

        return orderItemList;
    }

    /**
     * 判断商品是否存在、上下架状态、库存
     * @param cartVOList
     */
    private void vaildSaleStatusAndStock(List<CartVO> cartVOList) {
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            Product product = productFeignClient.detailForFeign(cartVO.getProductId());

            // 商品不存在且处于下架状态
            if (product == null || product.getStatus().equals(Constant.ProductStatus.NOT_SELL)) {
                throw new MallException(MallExceptionEnum.CART_PRODUCT_NOT_SELL);
            }
            // 库存数量不足
            if (product.getStock() < cartVO.getQuantity()) {
                throw new MallException(MallExceptionEnum.CART_NOT_ENOUGH);
            }
        }
    }
}
